///* File upload with jcrop*/
//
//// convert bytes into friendly format
//function bytesToSize(bytes) {
//    var sizes = ['Bytes', 'KB', 'MB'];
//    if (bytes == 0) return 'n/a';
//    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
//    return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i];
//};
//
//// update info by cropping (onChange and onSelect events handler)
//function updateInfo(e) {
//    $('#x1').val(e.x);
//    $('#y1').val(e.y);
//    $('#x2').val(e.x2);
//    $('#y2').val(e.y2);
//    $('#w').val(e.w);
//    $('#h').val(e.h);
//};
//
//// clear info by cropping (onRelease event handler)
//function clearInfo() {
//    $('.info #w').val('');
//    $('.info #h').val('');
//};
//
//// Create variables (in this scope) to hold the Jcrop API and image size
//var jcrop_api, boundx, boundy;
//
//function fileSelectHandler() {
//
//    // get selected file
//    var oFile = $('#avatarInputRegister')[0].files[0];
//
//    // hide all errors
//    $('.error').hide();
//
//    // check for image type (jpg and png are allowed)
//    var rFilter = /^(image\/jpeg|image\/png)$/i;
//    if (! rFilter.test(oFile.type)) {
//        $('.error').html('Please select a valid image file (jpg and png are allowed)').show();
//        return;
//    }
//
//    // check for file size
//    if (oFile.size > 250 * 1024) {
//        $('.error').html('You have selected too big file, please select a one smaller image file').show();
//        return;
//    }
//
//    // preview element
//    var oImage = document.getElementById('preview');
//
//    // prepare HTML5 FileReader
//    var oReader = new FileReader();
//        oReader.onload = function(e) {
//
//        // e.target.result contains the DataURL which we can use as a source of the image
//        oImage.src = e.target.result;
//        oImage.onload = function () { // onload event handler
//
//            // display step 2
//            //$('.step2').fadeIn(500);
//
//            // display some basic image info
//            var sResultFileSize = bytesToSize(oFile.size);
//
//            // destroy Jcrop if it is existed
//            if (typeof jcrop_api != 'undefined') {
//                jcrop_api.destroy();
//            }
//
//            setTimeout(function(){
//                // initialize Jcrop
//                $('#preview').Jcrop({
//                    minSize: [32, 32], // min crop size
//                    aspectRatio : 1, // keep aspect ratio 1:1
//                    bgFade: true, // use fade effect
//                    bgOpacity: .3, // fade opacity
//                    onChange: updateInfo,
//                    onSelect: updateInfo,
//                    onRelease: clearInfo
//                }, function(){
//
//                    // use the Jcrop API to get the real image size
//                    var bounds = this.getBounds();
//                    boundx = bounds[0];
//                    boundy = bounds[1];
//
//                    // Store the Jcrop API in the jcrop_api variable
//                    jcrop_api = this;
//                });
//            },1000);
//
//        };
//    };
//
//    // read selected file as DataURL
//    oReader.readAsDataURL(oFile);
//    
//    $('#cropImgPopin').modal('show');
//}

function initiaizeJcrop(element, updateInfo){
	$('#' + element).Jcrop({
		//boxWidth: 540, boxHeight: 300,
        minSize: [32, 32], // min crop size
        setSelect:   [ 150, 150, 50, 50 ], // default selection
        aspectRatio : 1, // keep aspect ratio 1:1
        bgFade: true, // use fade effect
        bgOpacity: .3, // fade opacity
        onChange: updateInfo,
        onSelect: updateInfo,
        onRelease: clearInfo
    }, function(){

        // use the Jcrop API to get the real image size
        var bounds = this.getBounds();
        boundx = bounds[0];
        boundy = bounds[1];

        // Store the Jcrop API in the jcrop_api variable
        jcrop_api = this;
    });
}

//clear info by cropping (onRelease event handler)
function clearInfo() {
  
};

/* Create variables (in this scope) to hold the Jcrop API and image size */
var jcrop_api, boundx, boundy;

ko.bindingHandlers.imageHandler = {
    update: function(element, valueAccessor, allBindings) {
        // First get the latest data that we're bound to
        var value = valueAccessor();
        //Next, whether or not the supplied model property is observable, get its current value
        var valueUnwrapped = ko.unwrap(value);
        
        // get selected file
        var oFile = $(element)[0].files[0];
        if(oFile === undefined){
        	return;
        }
        
        //check for image type (jpg and png are allowed)
        var rFilter = /^(image\/jpeg|image\/png)$/i;
        if (!rFilter.test(oFile.type)) {
        	if(valueUnwrapped.fail) valueUnwrapped.fail('InvalidImageType');
            return;
        }
        
        //check for file size - 2mb
        if (oFile.size > 2000000) {
        	if(valueUnwrapped.fail) valueUnwrapped.fail('InvalidImageSize');
            return;
        }
        
        //preview element
        var oImage = document.getElementById(valueUnwrapped.imageElement);
        
//        //prepare HTML5 FileReader
//        var oReader = new FileReader();
//        oReader.onload = function(e) {
//	        // e.target.result contains the DataURL which we can use as a source of the image
//	        oImage.src = e.target.result;
//	        oImage.onload = function () { // onload event handler
//	
//	            // destroy Jcrop if it is existed
//	            if (typeof jcrop_api != 'undefined') {
//	                jcrop_api.destroy();
//	            }
//	            var element = valueUnwrapped.imageElement;
//	            var onChange = valueUnwrapped.onCropChange;
//	            setTimeout(initiaizeJcrop(element, onChange),1000);
//	        };
//        };
        
        
        var oReader = new FileReader();
        oReader.onloadend = function(){
	    	var tempImg = new Image();
	        tempImg.src = oReader.result;
	        tempImg.onload = function() {
	     
	            var MAX_WIDTH = 300;
	            var MAX_HEIGHT = 200;
	            var tempW = tempImg.width;
	            var tempH = tempImg.height;
	            if (tempW > tempH) {
	                if (tempW > MAX_WIDTH) {
	                   tempH *= MAX_WIDTH / tempW;
	                   tempW = MAX_WIDTH;
	                }
	            } else {
	                if (tempH > MAX_HEIGHT) {
	                   tempW *= MAX_HEIGHT / tempH;
	                   tempH = MAX_HEIGHT;
	                }
	            }
	     
	            var canvas = document.createElement('canvas');
	            canvas.width = tempW;
	            canvas.height = tempH;
	            var ctx = canvas.getContext("2d");
	            ctx.drawImage(this, 0, 0, tempW, tempH);
	            var dataURL = canvas.toDataURL("image/jpeg");
	            oImage.src = dataURL;
				oImage.onload = function() { // onload event handler

					// destroy Jcrop if it is existed
					if (typeof jcrop_api != 'undefined') {
						jcrop_api.destroy();
					}
					var element = valueUnwrapped.imageElement;
					var onChange = valueUnwrapped.onCropChange;
					setTimeout(initiaizeJcrop(element, onChange), 1000);
				};
	        };
        };
        
        
        // read selected file as DataURL
        oReader.readAsDataURL(oFile);
        
        if(valueUnwrapped.done) valueUnwrapped.done();
    }
};